<template>
  <view>
    <!-- 收货地址 -->
    <view class="addr" @tap="selectAddress" v-if="addressList.length > 0">
      <view class="icon">
        <image src="../../static/img/addricon.png" mode=""></image>
      </view>
      <view class="right">
        <view class="tel-name">
          <view class="name">
            {{ recinfo.name }}
          </view>
          <view class="tel">
            {{ recinfo.phone }}
          </view>
        </view>
        <view class="addres">
          {{ recinfo.region }}
          {{ recinfo.address }}
        </view>
      </view>
    </view>
    <view class="addr" @tap="selectAddress" v-else>
      <view>暂无收货地址，请点击填写</view>
    </view>

    <!-- 购买商品列表 -->
    <view class="buy-list">
      <view class="row" v-for="(row, index) in buylist" :key="index">
        <view class="goods-info">
          <view class="img">
            <image
              :src="
                row.pImgUrl
                  ? BASE_URL + row.pImgUrl.split(',')[0]
                  : '/static/img/category/3.png'
              "
            ></image>
          </view>
          <view class="info">
            <view class="title">{{ row.pName }}</view>
            <view class="spec"
              >选择{{ row.pSpecifications }} 数量:{{ row.number }}</view
            >
            <view class="price-number">
              <view class="price"
                >￥{{ calculateItemTotal(row.pPrice, row.number) }}</view
              >
              <view class="number"> </view>
            </view>
          </view>
        </view>
      </view>
    </view>
    <view class="detail">
      <view class="row">
        <view class="nominal"> 商品金额 </view>
        <view class="content"> ￥{{ goodsPrice | toFixed }} </view>
      </view>
    </view>
    <view class="blck"> </view>
    <view class="footer">
      <view class="settlement">
        <view class="sum"
          >合计:<view class="money">￥{{ sumPrice | toFixed }}</view></view
        >
        <view class="btn" @tap="toPay">提交订单</view>
      </view>
    </view>
  </view>
</template>

<script>
import { creatOrder } from "@/common/api/orderList.js";
import { getAddressList } from "@/common/api/address.js";
import { deleteCart, deleteCartList } from "@/common/api/car.js";
import {
  add,
  subtract,
  multiply,
  calculateOrderTotal,
  safeNumber,
} from "@/common/utils/precision.js";
import { BASE_URL } from "@/common/utils/request.js";
export default {
  data() {
    return {
      buylist: [], //订单列表
      goodsPrice: 0.0, //商品合计价格
      sumPrice: 0.0, //用户付款价格
      freight: 12.0, //运费
      note: "", //备注
      int: 1200, //抵扣积分
      deduction: 0, //抵扣价格
      recinfo: {},
      customerId: "", // 客户ID，需要从登录信息中获取
      addressId: "",
      productFlag: false,
      addressList: [],
      BASE_URL: BASE_URL,
    };
  },
  async created() {
    this.customerId = uni.getStorageSync("userInfo").id || "";
    // 加载地址列表 选出默认地址
    this.loadAddressList();
  },
  onLoad(option) {
    this.productFlag = option.productFlag; //是否从详情页面购买还是 购物车购买
  },
  onShow() {
    //页面显示时，加载订单信息 - 使用精度工具避免浮点数精度问题
    uni.getStorage({
      key: "buylist",
      success: (ret) => {
        this.buylist = ret.data;

        // 使用精度工具计算商品总价
        this.goodsPrice = calculateOrderTotal(
          this.buylist.map((item) => ({
            quantity: safeNumber(item.number, 0),
            price: safeNumber(item.pPrice, 0),
          })),
          2
        );

        // 使用精度工具计算最终价格
        this.deduction = safeNumber(this.int / 100, 0);
        this.sumPrice = add(
          subtract(this.goodsPrice, this.deduction, 2),
          safeNumber(this.freight, 0),
          2
        );
      },
    });
    uni.getStorage({
      key: "selectAddress",
      success: (e) => {
        console.log(e, "555555555");
        this.recinfo = e.data;
        this.addressId = e.data.id;
        this.addressList = [e.data];
        uni.removeStorage({
          key: "selectAddress",
        });
      },
    });
  },
  onBackPress() {
    //页面后退时候，清除订单信息
    this.clearOrder();
  },
  filters: {
    toFixed: function (x) {
      return parseFloat(x).toFixed(2);
    },
  },
  methods: {
    // 计算单项商品总价 - 使用精度工具
    calculateItemTotal(price, quantity) {
      const safePrice = safeNumber(price, 0);
      const safeQuantity = safeNumber(quantity, 0);
      const total = multiply(safePrice, safeQuantity, 2);
      return total.toFixed(2);
    },
    // 加载地址列表
    loadAddressList() {
      if (!this.customerId) {
        console.log("客户ID未获取到");
        return;
      }

      uni.showLoading({
        title: "加载中...",
      });

      getAddressList(this.customerId)
        .then((res) => {
          uni.hideLoading();
          if (res.data.ok) {
            this.addressList = res.data.data || [];
            this.addressListFunc();
          }
        })
        .catch((err) => {
          uni.hideLoading();
          uni.showToast({
            title: "加载地址列表失败",
            icon: "none",
          });
          console.error("加载地址列表失败:", err);
        });
    },
    addressListFunc() {
      const some = this.addressList.some((item) => {
        return item.isDefault;
      });
      if (this.addressList.length > 0) {
        if (some) {
          this.recinfo = this.addressList.find((u) => u.isDefault);
          this.addressId = this.recinfo.id;
        } else {
          this.recinfo = this.addressList[0];
          this.addressId = this.recinfo.id;
        }
      }
    },
    // 删除购物车信息
    deleteCartFun() {
      return new Promise((resolve) => {
        const orderIdList = [];
        this.buylist.forEach((element) => {
          orderIdList.push(element.id);
        });
        deleteCartList(this.customerId, orderIdList).then((res) => {
          resolve(res);
        });
      });
    },
    creatOrderFun() {
      const orderItems = this.buylist.map((item) => {
        const temItem = {
          productId: item.productId,
          pNumber: item.number,
          pPrice: item.pPrice,
        };
        return temItem;
      });
      const params = {
        customerId: this.customerId,
        addressId: this.addressId,
        orderItems: orderItems,
        remark: "",
      };
      return new Promise((resolve) => {
        creatOrder(params).then((res) => {
          resolve(res);
        });
      });
    },
    clearOrder() {
      uni.removeStorage({
        key: "buylist",
        success: (res) => {
          this.buylist = [];
          console.log("remove buylist success");
        },
      });
    },
    async toPay() {
      //商品列表
      let paymentOrder = [];
      let len = this.buylist.length;
      for (let i = 0; i < len; i++) {
        paymentOrder.push(this.buylist[i]);
      }
      if (paymentOrder.length == 0) {
        uni.showToast({ title: "订单信息有误，请重新购买", icon: "none" });
        return;
      }
      console.log(this.addressId, "this.addressIdthis.addressId");
      if (this.addressId == "") {
        uni.showToast({ title: "请输入地址", icon: "none" });
        return;
      }
      //本地模拟订单提交UI效果
      uni.showLoading({
        title: "正在提交订单...",
      });
      const creatRes = await this.creatOrderFun();
      if (creatRes.data.ok) {
        uni.hideLoading();
        uni.showToast({
          title: "订单创建成功",
        });
        if (!this.productFlag) {
          await this.deleteCartFun();
        }
        uni.navigateTo({
          url: "/pages/user/order_list/order_list",
        });
      } else {
        uni.showToast({
          title: "订单创建失败",
        });
      }
    },
    //选择收货地址
    selectAddress() {
      uni.navigateTo({
        url: "../user/address/address?type=select",
      });
    },
  },
};
</script>

<style lang="scss">
.addr {
  width: 86%;
  padding: 20upx 3%;
  margin: 30upx auto 20upx auto;
  box-shadow: 0upx 5upx 20upx rgba(0, 0, 0, 0.1);
  border-radius: 20upx;
  display: flex;
  .icon {
    width: 80upx;
    height: 80upx;
    display: flex;
    align-items: center;
    image {
      width: 60upx;
      height: 60upx;
    }
  }
  .tel-name {
    width: 100%;
    display: flex;
    font-size: 32upx;
    .tel {
      margin-left: 40upx;
    }
  }
  .addres {
    width: 100%;
    font-size: 26upx;
    color: #999;
  }
}
.buy-list {
  width: 86%;
  padding: 10upx 3%;
  margin: 30upx auto 20upx auto;
  box-shadow: 0upx 5upx 20upx rgba(0, 0, 0, 0.1);
  border-radius: 20upx;
  .row {
    margin: 30upx 0;
    .goods-info {
      width: 100%;
      display: flex;
      .img {
        width: 22vw;
        height: 22vw;
        border-radius: 10upx;
        overflow: hidden;
        flex-shrink: 0;
        margin-right: 10upx;
        image {
          width: 22vw;
          height: 22vw;
        }
      }
      .info {
        width: 100%;
        height: 22vw;
        overflow: hidden;
        display: flex;
        flex-wrap: wrap;
        position: relative;
        .title {
          width: 100%;
          font-size: 28upx;
          display: -webkit-box;
          -webkit-box-orient: vertical;
          -webkit-line-clamp: 2;
          // text-align: justify;
          overflow: hidden;
        }
        .spec {
          font-size: 22upx;
          background-color: #f3f3f3;
          color: #a7a7a7;
          height: 40upx;
          display: flex;
          align-items: center;
          padding: 0 10upx;
          border-radius: 20upx;
          margin-bottom: 20vw;
        }
        .price-number {
          position: absolute;
          width: 100%;
          bottom: 0upx;
          display: flex;
          justify-content: space-between;
          align-items: flex-end;
          font-size: 28upx;
          height: 40upx;
          .price {
            color: #f06c7a;
          }
          .number {
            display: flex;
            justify-content: center;
            align-items: center;
          }
        }
      }
    }
  }
}
.order {
  width: 86%;
  padding: 10upx 3%;
  margin: 30upx auto 20upx auto;
  box-shadow: 0upx 5upx 20upx rgba(0, 0, 0, 0.1);
  border-radius: 20upx;
  .row {
    margin: 20upx 0;
    height: 40upx;
    display: flex;
    .left {
      font-size: 28upx;
    }
    .right {
      margin-left: 40upx;
      font-size: 26upx;
      color: #999;
      input {
        font-size: 26upx;
        color: #999;
      }
    }
  }
}
.blck {
  width: 100%;
  height: 100upx;
}
.footer {
  width: 92%;
  padding: 0 4%;
  background-color: #fbfbfb;
  height: 100upx;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  font-size: 28upx;
  position: fixed;
  bottom: 0upx;
  z-index: 5;

  .settlement {
    width: 80%;
    display: flex;
    justify-content: flex-end;
    align-items: center;
    .sum {
      width: 50%;
      font-size: 28upx;
      margin-right: 10upx;
      display: flex;
      justify-content: flex-end;
      .money {
        font-weight: 600;
      }
    }
    .btn {
      padding: 0 30upx;
      height: 60upx;
      background-color: #f06c7a;
      color: #fff;
      display: flex;
      justify-content: center;
      align-items: center;
      font-size: 30upx;
      border-radius: 40upx;
    }
  }
}
.detail {
  width: 86%;
  padding: 10upx 3%;
  margin: 30upx auto 20upx auto;
  box-shadow: 0upx 5upx 20upx rgba(0, 0, 0, 0.1);
  border-radius: 20upx;
  .row {
    height: 60upx;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .nominal {
      font-size: 28upx;
    }
    .content {
      font-size: 26upx;
      color: #f06c7a;
    }
  }
}
</style>
